package doan.chuyennganh.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import doan.chuyennganh.model.Student;

public class ClassDataSource {
	public String TABLE_NAME = "tblClass";
	public static final String COLUMN_MSSV = "_id";
	public static final String COLUMN_TEN = "name";
	public static final String COLUMN_LOP = "class";
	private int dbVersion;
	private ArrayList<Student> listStudent = new ArrayList<Student>();
	// Database creation sql statement
	private  String CREATE_TABLE = "CREATE TABLE "
	      + TABLE_NAME
	      + "(" + ClassDataSource.COLUMN_MSSV + " TEXT PRIMARY KEY, " 
	      + ClassDataSource.COLUMN_TEN + " TEXT, "
	      + ClassDataSource.COLUMN_LOP + " TEXT "
	      + ")";

	// Database fields
	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;
	private Set<String> tableNames = new HashSet<String>();
	private String[] allColumns = { ClassDataSource.COLUMN_MSSV,
			ClassDataSource.COLUMN_TEN, ClassDataSource.COLUMN_LOP };

	public ClassDataSource(Context context, String tableName) {
		TABLE_NAME = tableName;
		CREATE_TABLE = "CREATE TABLE "
			      + TABLE_NAME
			      + "(" + ClassDataSource.COLUMN_MSSV + " TEXT, " 
			      + ClassDataSource.COLUMN_TEN + " TEXT, "
			      + ClassDataSource.COLUMN_LOP + " TEXT "
			      + ")";
		SharedPreferenceHelper pre = new SharedPreferenceHelper(context);
		dbVersion = pre.getInt(Constants.DATABASE_VERSION, 1);
		tableNames = pre.getStringSet(Constants.DATABASE_TABLES, new HashSet<String>());
		if(!tableNames.contains(tableName)){
			dbVersion += 1;
			tableNames.add(tableName);
			pre.putInt(Constants.DATABASE_VERSION, dbVersion);
			pre.putStringSet(Constants.DATABASE_TABLES, tableNames);
		}
		Log.d("DBVERSION", dbVersion + "");
		dbHelper = new DatabaseHelper(context, TABLE_NAME, CREATE_TABLE, dbVersion);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
		listStudent = (ArrayList<Student>)getAllStudents();
	}

	public void close() {
		dbHelper.close();
	}

	public long insertStudent(Student student) {
		ContentValues values = new ContentValues();
		values.put(ClassDataSource.COLUMN_MSSV, student.getMaSV());
		values.put(ClassDataSource.COLUMN_TEN, student.getHoten());
		values.put(ClassDataSource.COLUMN_LOP, student.getLop());
		return database.insert(TABLE_NAME, null,values);
//		long insertId = database.insert(DatabaseHelper.TABLE_NAME, null,
//				values);
//		Cursor cursor = database.query(DatabaseHelper.TABLE_NAME,
//				allColumns, DatabaseHelper.COLUMN_MSSV + " = " + insertId, null,
//				null, null, null);
//		cursor.moveToFirst();
//		Student newStudent = cursorToStudent(cursor);
//		cursor.close();
//		return newStudent;
	}

	public void deleteStudent(Student student) {
		String id = student.getMaSV();
		if(getStudent(student.getMaSV()) == null){
			return;
		}
		database.delete(TABLE_NAME, ClassDataSource.COLUMN_MSSV
				+ " = " + id, null);
	}
	
	public void deleteStudent(String studentID) {
		if(getStudent(studentID) == null){
			return;
		}
		database.delete(TABLE_NAME, ClassDataSource.COLUMN_MSSV
				+ " = " + studentID, null);
	}
	
	private Student getStudent(String id){
		for(Student st :listStudent){
			if(st.getMaSV().equalsIgnoreCase(id)){
				return st;
			}
		}
		return null;
	}
	
	public int updateStudent(Student student)
	  {
		if(getStudent(student.getMaSV()) == null){
			return -1;
		}
	   ContentValues cv=new ContentValues();
	   cv.put(ClassDataSource.COLUMN_TEN, student.getHoten());
	   cv.put(ClassDataSource.COLUMN_LOP, student.getLop());
	   return database.update(TABLE_NAME, cv, ClassDataSource.COLUMN_MSSV + "=?", new String []{String.valueOf(student.getMaSV())});   
	  }
	public int updateValue(String id,String column, boolean value) {
		if(getStudent(id) == null){
			return -1;
		}
		ContentValues cv=new ContentValues();
		   cv.put(column, value);
		   return database.update(TABLE_NAME, cv, ClassDataSource.COLUMN_MSSV + "=?", new String []{String.valueOf(id)});
	}
	public List<Student> getAllStudents() {
		List<Student> Students = new ArrayList<Student>();
		
		Cursor cursor = database.query(TABLE_NAME,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Student Student = cursorToStudent(cursor);
			Students.add(Student);
			cursor.moveToNext();
		}
		// make sure to close the cursor
		cursor.close();
		return Students;
	}
	
	public void insertColumn(String new_col ,  ArrayList<String> checkList) {
		
		Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME + " LIMIT 0", null);
		Log.d("COLUMNS", cursor.getColumnNames().toString());
		String[] colNames = cursor.getColumnNames();
		boolean isColumnExist = false;
		for(String col : colNames){
			if(col.equalsIgnoreCase(new_col)){
				isColumnExist = true;
				break;
			}
		}
		
		if(!isColumnExist){
			String INSERT_COLUMN = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+ new_col +" BOOL DEFAULT (0)";
			database.execSQL(INSERT_COLUMN);
		}
		
		for(String ms : checkList){
			updateValue(ms, new_col, true);
		}
	}
	
	private Student cursorToStudent(Cursor cursor) {
		Student student = new Student();
		student.setMaSV(cursor.getString(0));
		student.setHoten(cursor.getString(1));
		student.setLop(cursor.getString(2));
		return student;
	}
	
	public String[] getAllColumnsName() {
		Cursor dbCursor = database.query(TABLE_NAME, null, null, null, null, null, null);
		String[] columnNames = dbCursor.getColumnNames();
		return columnNames;
	}
	
	public void createExample() {
		Student st1 = new Student("10222222", "Van Anh", "DHTH6A");
		Student st2 = new Student("10233333", "Van Em", "DHTH6A");
		Student st3 = new Student("10444444", "Van Chi", "DHTH6D");
		Student st4 = new Student("10555555", "Van Chau", "DHTH6A");
		Student st5 = new Student("10211111", "Van Van", "DHTH6B");
		insertStudent(st1);
		insertStudent(st2);
		insertStudent(st3);
		insertStudent(st4);
		insertStudent(st5);
	}
}
